package com.mischa.doedeljas.client;

import java.net.Socket;
import java.util.Vector;

import javax.swing.JOptionPane;

import com.mischa.doedeljas.Card;
import com.mischa.doedeljas.Card.Suit;
import com.mischa.doedeljas.client.ui.ConnectionDialog;
import com.mischa.doedeljas.client.ui.DealerDialog;
import com.mischa.doedeljas.Messages;
import com.mischa.network.SocketIO;

public class Game extends SocketIO 
{
	private DoedelJas _ui;
	
	private int _gameId;	
	
	private Vector<Card> _hand;	
	private Suit _trump;

	private boolean _showDealerDialog;
	
	public Game(Socket socket, DoedelJas UI) {
		super(socket);		
		_ui = UI;
	}	

	@Override
	public synchronized void messageReceived(int message, int[] arguments) 
	{
		System.out.println("Message: " + message);
		
		switch(message)
		{		
		case Messages.JOINED:
			_gameId = arguments[0];
			_ui.showMessage("You have joined game #" + _gameId, "Game joined.", false);
			break;
			
		case Messages.YOU_DEAL:
			_showDealerDialog = true;
			
			break;
			
		case Messages.DEALT:
			_hand = new Vector<Card>();
			
			for (int i = 0; i < arguments.length; ++i)
			{
				_hand.add(new Card(arguments[i]));
			}
			
			_ui.handUpdated(_hand, _trump);			
			break;
			
		case Messages.TRUMP:
			_trump = Suit.fromInteger(arguments[0]);
			_ui.handUpdated(_hand, _trump);
			JOptionPane.showMessageDialog(_ui, _trump.toString() + " is trump!");			
			break;
		
		case Messages.TRICK:
			_ui.showTrick(arguments[0] - 1, new Card[] { 
					 arguments[1] == Messages.NONE ? null : new Card(arguments[1]),
					 arguments[2] == Messages.NONE ? null : new Card(arguments[2]),
					 arguments[3] == Messages.NONE ? null : new Card(arguments[3])
			});

			break;
		}
		
		if (_showDealerDialog && _hand.size() > 0)
		{
			DealerDialog dealerDialog = new DealerDialog(_ui);
			dealerDialog.setGame(this);
			dealerDialog.setHand(_hand);			
			dealerDialog.setVisible(true);
			
			_showDealerDialog = false;
		}
	}

	public void play(Card selectedCard) {
		if (_hand.contains(selectedCard))
		{
			sendMessage(Messages.PLAY, selectedCard.toInteger());
		}
	}

	public void dumpAndTrump(Suit trumpSuit, Card dumped1, Card dumped2) {
		sendMessage(Messages.DUMP, new int[] { dumped1.toInteger(), dumped2.toInteger() });
		sendMessage(Messages.TRUMP, trumpSuit.toInteger());
	}
}